package edu.uow.devdocs

import grails.converters.JSON

class DevelopmentChecklistController {
    static scaffold = true
	
	def ajaxGetDevelopmentChecklists(Integer id, String update) {
		def list = DevelopmentChecklist.findAllByDevelopmentTask(DevelopmentTask.get(id))
		def result = ['id':update, 'data':
		list.collect() {
			[
				id:it.id,
				description:it.description
			]
		}]
		render result as JSON
	}
	
	def addChecklist() {
		def developmentChecklistInstance = new DevelopmentChecklist()
		print params
		def checklist = Checklist.get(params?.checklist.id)
		def developmentTask = DevelopmentTask.get(params?.developmentTask.id)
		developmentChecklistInstance.checklist = checklist
		developmentChecklistInstance.description = checklist.description
		developmentChecklistInstance.checklistContent = checklist.checklist
		developmentChecklistInstance.status = DevelopmentChecklistStatus.findByStatus('New')
		developmentChecklistInstance.developmentTask = developmentTask
		developmentChecklistInstance.project = developmentTask.project
		developmentTask.addToDevelopmentChecklists(developmentChecklistInstance)
		//developmentChecklistInstance.save()
		if (developmentTask.save(flush:true) ){
			flash.message = checklist.description + " added"
			
		}
		redirect(controller: 'developmentTask', action: 'edit',	id: developmentTask?.id, fragment: 'tabChecklist')
		//render(template:"/shared/addChecklist", model:['developmentTaskInstance':developmentTask])
		
	}
	
	def getDevelopmentChecklist() {
		def developmentChecklist = DevelopmentChecklist.get(params?.id)
		render(template:"/shared/editDevelopmentChecklist",model:['developmentChecklistInstance':developmentChecklist])
	}
	
	def delete() {
		def developmentChecklist = DevelopmentChecklist.get(params?.id)
		def developmentTask = developmentChecklist.developmentTask
		developmentTask.removeFromDevelopmentChecklists(developmentChecklist)
		if (developmentTask.save()) {
			flash.message = developmentChecklist.description + " deleted"
		}
		developmentChecklist.delete()
		render(template:"/shared/addChecklist", model:['developmentTaskInstance':developmentTask])
	}
	
	def saveChecklist() {
		def developmentChecklist = DevelopmentChecklist.get(params?.id)
		println params
		bindData(developmentChecklist,params)
		if (developmentChecklist.save(flush:true)) {
			flash.message = message(code: 'default.updated.message', args: [message(code: 'developmentChecklist.label', default: 'DevelomentChecklist'), developmentChecklist.id])
		}
		render(template:"/shared/editDevelopmentChecklist",model:['developmentChecklistInstance':developmentChecklist])
	}
	
	def preview() {
		params.previewId.each{
			def developmentChecklist = DevelopmentChecklist.get(it)
			render (template:"preview",model:['developmentChecklistInstance':developmentChecklist])
		}
	}
}
